import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import { inject, observer } from 'mobx-react';
import { Input, Button } from 'antd';
import './chat.scss'

@inject('user')
@observer
export default class Home extends Component {
  static displayName = 'Home'

  constructor(props) {
    super(props);
    this.state = {
      txt: '',
      ws: '',
      list: [],
      scroll: 0
    };
  }
  componentWillMount () {
    const ws = new WebSocket('ws://134.175.145.32:8088')
    // const ws = new WebSocket('ws://172.16.110.166:8088')
    this.setState({ws: ws})
    ws.addEventListener('open', function () {
      // that.ws.send(that.txt)
    })
    ws.onmessage = (msg) => {
      let res = JSON.parse(msg.data)
      // if (res.to === that.userInfo.account) {
      //   if (that.chatRoom.findIndex(v => {
      //     return v === res.from
      //   }) === -1) {
      //     that.chatRoom.push(res.from)
      //   }
      // }
      let list = this.state.list
      list.push(res)
      this.setState({list, scroll: this.state.scroll + 100})
      const nodeList = document.querySelector('.list')
      nodeList.scrollTo(0, this.state.scroll)
      // that.$nextTick(() => {
      //   const nodeList = document.querySelectorAll('.msg')
      //   nodeList.forEach(v => {
      //     v.scrollTo(0, that.scroll)
      //   })
      // })
    }
    this.setState({ws})
  }
  send = () => {
    if (!this.state.txt) return
    let item = {
      ...this.props.user.info,
      txt: this.state.txt,
    }
    this.state.ws.send(JSON.stringify(item))
    this.setState({txt: ''})
  }
  render() {
    const user = this.props.user;
    return (
      <div className="chatRoom">
        <div className="list">
        {this.state.list.map((v, i)=>{
          return(
              <div key={i}>
                <div>
                  <span>{v.account}</span>
                  <img src={v.img} alt=""/>
                </div>
                <p className={this.props.user.info.account === v.account?'me':''}>{v.txt}</p>
              </div>
          )
        })}
        </div>
        <div className="btm">
          <Input value={this.state.txt} onChange={e => {this.setState({txt: e.target.value.trim()})}}/>
          <Button type="primary" onClick={this.send}>发送</Button>
        </div>
      </div>
    );
  }
}
